﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Linq;
using System.Collections.Generic;
using System;
using AutoMapper;

using System.ComponentModel.DataAnnotations;
using Cctegaq.Api.Configurations;


using System.Security.Cryptography.X509Certificates;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

using LinqKit;
using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

using Cari.IBP.Platform.Sidecar;
using Cari.IBP.Platform.Utility;

using Ccteg.Common;
using CCcteg.Common;
using Ccteg.DB;
using Microsoft.AspNetCore.Authorization;

namespace Cctegaq.Api.Controllers
{



    /// <summary>
    /// 法律法规
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class LAWController : IbpControllerBase
    {
        private readonly AppAuthenticationSettings _appSettings;
        private readonly MySqlDbContext _dbContext;
        private readonly IMapper _mapper;
        private readonly ApplicationData _applicationData;
        private readonly MySqlDbContext_SFM _dbContext_SFM;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="appSettings"></param>
        /// <param name="dbContext"></param>
        /// <param name="dbContext_SFM"></param>
        /// <param name="mapper"></param>
        /// <param name="applicationData"></param>
        public LAWController(IOptions<AppAuthenticationSettings> appSettings, MySqlDbContext dbContext, MySqlDbContext_SFM dbContext_SFM, IMapper mapper, ApplicationData applicationData)
        {
            _appSettings = appSettings.Value;
            _dbContext = dbContext;
            _mapper = mapper;
            _applicationData = applicationData;
            _dbContext_SFM = dbContext_SFM;
        }

        /// <summary>
        /// 法律法规查询
        /// </summary>
        /// <param name="lawname">法律法规标准名称</param>
        /// <param name="trade">行业</param>
        /// <param name="level">级别(国家级,部位级)</param>
        /// <param name="state">审核状态</param>
        /// <param name="substate">下发状态</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">显示条数</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [ResourceDeclare(Identity = "law/law/list", Name = "法律法规查询", Operation = Constants.OPERATION_BROWSE)]
        [ResourceDeclare(Identity = "law/law/approve", Name = "法律法规审核", Operation = Constants.OPERATION_BROWSE)]
        public ResponseResultModel<IEnumerable<Law_Law_ViewModel>> LawLawSearch(string lawname, string trade, string level, string state, string substate, int pageindex = 1, int pagesize = 10)
        {
            using (_dbContext)
            {

                //  var dd = _applicationData.GetServiceLocate("LAW");
                var response = ResponseModelFactory<IEnumerable<Law_Law_ViewModel>>.CreateResultInstance;
                Expression<Func<law_law, bool>> where = p => true;

                //根据法律法规过滤
                where = where.CheckNullAnd(x => x.LawName.Contains(lawname), lawname);
                where = where.CheckNullAnd(x => x.Level == level, level);

                where = where.CheckNullAnd(x => x.SubState == substate, substate);
                where = where.CheckNullAnd(x => x.State == state, state);
                //根据行业过滤
                where = where.CheckNullAnd(x => x.Trade.Contains(trade), trade);

                where = where.And(x => x.Deleted == false);

                var query = _dbContext.Law_Law.AsQueryable();

                query = query.Where(where.Expand()).OrderByDescending(x => x.Id);

                var list = query.Paged(pageindex, pagesize).ToList();
                var totalCount = query.Count();
                var data = list.Select(_mapper.Map<law_law, Law_Law_ViewModel>);
                response.SetData(data, totalCount);
                return response;
            }

        }

        ///<summary>
        /// 法律法规删除
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
        //  [ResourceDeclare(Identity = "/LAW", Name = "法律法规删除", Operation = Constants.OPERATION_DELETE)]
        public ResponseModel DeleteLawLaw([Required] int id)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var res = _dbContext.Law_Law.Where(x => x.Id == id)
                          .SetField(x => x.Deleted).WithValue(true)
                          .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                          .SetField(x => x.ModifiedBy).WithValue("系统")
                          .Update();
                    if (res > 0)
                        response.SetSuccess("删除成功");
                    else
                        response.SetFailed("删除失败");

                }

            }
            catch (Exception ex)
            {
                response.SetFailed("删除失败");
                response.Data = ex.Message;
            }
            return response;
        }

        /// <summary>
        ///下发
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
        //  [ResourceDeclare(Identity = "/LAW", Name = "下发", Operation = "下发")]
        public ResponseModel UpdateSubState([Required] int id)
        {
            var response = ResponseModelFactory.CreateInstance;
            using (_dbContext)
            {
                var entity = _dbContext.Law_Law.FirstOrDefault(x => x.Id == id);
                if (entity == null)
                {
                    response.SetFailed("下发失败,该条数据不存在");
                    return response;
                }
                if (entity.State == "审核通过" && entity.SubState == "已下发")
                {
                    response.SetFailed("本条记录已通过,已下发,不能再次审核。");
                    return response;
                }
                if (entity.State == "未审核")
                {
                    response.SetFailed("正在审核中,不能再次下发");
                    return response;
                }
                if (entity.State == "审核拒绝")
                {
                    response.SetFailed("审核拒绝,不能再次下发");
                    return response;
                }
                //调用kafak 下发成功后更新状态 提供公用方法
                entity.SubState = "已下发";
                entity.SubDate = DateTime.Now;
                entity.ModifiedBy = "系统";
                entity.ModifiedOn = DateTime.Now;
                if (_dbContext.SaveChanges() > 0)
                {
                    response.SetFailed("下发成功");

                }
                else
                {
                    response.SetFailed("下发失败");
                }
            }


            return response;
        }

        /// <summary>
        /// 法律法规统计
        /// </summary>
        /// <returns></returns>
      //  [ResourceDeclare(Identity = "/LAW", Name = "法律法规统计", Operation = Constants.OPERATION_BROWSE)]
        [HttpGet]
        public ResponseResultModel<IEnumerable<LawLawSearchStatistics_ViewModel>> LawLawSearchStatistics()
        {
            using (_dbContext)
            {
                Expression<Func<law_law, bool>> where = p => true;
                where = where.And(x => x.Deleted == false).And(x => x.Level != null);
                var query = _dbContext.Law_Law.AsQueryable().Where(where.Expand()).GroupBy(x => x.Level).Select(group => new LawLawSearchStatistics_ViewModel { Name = group.Key, Count = group.Count() });
                var response = ResponseModelFactory<IEnumerable<LawLawSearchStatistics_ViewModel>>.CreateResultInstance;
                response.SetData(query, query.Count());
                return response;
            }

        }


        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="state">传入状态(审核通过或审核拒绝)</param>
        /// <param name="nopasscontents">传入拒绝原因 审核拒绝时传入</param>
        /// <returns></returns>
        [HttpPost]

        //[ResourceDeclare(Identity = "/LAW", Name = "审批", Operation = "审批")]
        public ResponseModel UpdateState([Required] int id, [Required] string state, string nopasscontents)
        {

            state = state.Trim();
            var response = ResponseModelFactory.CreateInstance;
            response.SetFailed("审核失败");

            if (state == "审核通过" || state == "审核拒绝")
            { }
            else
                return response;


            using (_dbContext)
            {

                var entity = _dbContext.Law_Law.FirstOrDefault(x => x.Id == id);

                if (entity == null)
                {
                    response.SetFailed("审核失败,该条数据不存在");
                    return response;
                }
                if (entity.State == "审核通过")
                {
                    response.SetFailed("本条记录审核已通过,不能再次审核。");
                    return response;
                }
                entity.State = state;
                entity.Checker = CurrentUser.UserInfo?.UserName;
                entity.PassDate = DateTime.Now;
                entity.ModifiedBy = CurrentUser.UserInfo?.UserName;
                entity.ModifiedOn = DateTime.Now;


                if (state == "审核通过")
                {
                    try
                    {
                        entity.NoPassContents = "";
                        entity.SubState = "已下发";
                        entity.SubDate = DateTime.Now;

                        var sfmjobEntity = new sfm_job();
                        sfmjobEntity.TimeStamp = DateTime.Now;
                        sfmjobEntity.DataId = id;
                        sfmjobEntity.Topic = SendJobTopic.常州;
                        sfmjobEntity.OperateType = "Add";
                        sfmjobEntity.DataType = SendJobDataType.LAW001.ToString();
                        sfmjobEntity.Status = 0;
                        sfmjobEntity.TableName = "law_law";
                        sfmjobEntity.JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(new SendKafakJobModel() { Data = entity, OperateType = sfmjobEntity.OperateType, DataType = sfmjobEntity.DataType, TimeStamp = sfmjobEntity.TimeStamp });

                        if (_dbContext.SaveChanges() > 0)
                        {
                            _dbContext_SFM.sfm_job.Add(sfmjobEntity);
                            _dbContext_SFM.SaveChanges();
                            response.SetData("审核成功");
                        }

                    }
                    catch (Exception ex)
                    {
                        response.Code = 999;
                        response.Message = "审核失败";
                        response.Data = ex.Message;
                    }

                }
                else if (state == "审核拒绝")
                {
                    entity.NoPassContents = nopasscontents;
                    _dbContext.SaveChanges();
                }
            }
            return response;
        }


        /// <summary>
        /// 法律法规添加,修改
        /// </summary>
        /// <param name="model">model.id大于0修改,新增传0</param>
        /// <returns></returns>
        [HttpPost]
        [ModelValidationAttribute]
        //[ResourceDeclare(Identity = "/LAW", Name = "法律法规添加,修改", Operation = Constants.OPERATION_ADD)]
        public ResponseModel LawLawAddOrUpdate([FromBody] Law_Law_ViewModel model)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var entity = _mapper.Map<Law_Law_ViewModel, law_law>(model);
                    if (entity.Id > 0)
                    {
                        if (_dbContext.Law_Law.AsNoTracking().Any(x => x.Id != model.Id && x.LawName == model.LawName.Trim() && x.Deleted == false))
                        {
                            response.SetFailed("此法律法规已存在");
                            return response;
                        }
                        //这里有个坑 如果不加AsNoTracking 相同的id查询 就会从orm 中取   当  外层Attach
                        var checkentity = _dbContext.Law_Law.AsNoTracking().Where(x => x.Id == model.Id && x.Deleted == false).FirstOrDefault();
                        if (checkentity.State == "审核通过")
                        {
                            response.SetFailed("此法律法规审核已通过,不能修改。");
                            return response;
                        }
                        //要修改的类型
                        _dbContext.ModifyEntityValue(entity, x => new
                        {
                            x.LawName,
                            x.LawType,
                            x.Publish,
                            x.Trade,
                            x.Level,
                            x.File,
                            x.Year,
                            x.Version,
                            x.NewDoDate,
                            x.NewUpdateDate,
                            x.Remark
                        });
                        if (checkentity.State == "审核拒绝")
                        {
                            entity.State = "未审核";
                        }
                        entity.ModifiedBy = CurrentUser.UserInfo?.UserName;
                        entity.ModifiedOn = System.DateTime.Now;
                        _dbContext.SaveChanges();
                    }
                    else
                    {
                        if (_dbContext.Law_Law.Any(x => x.LawName == model.LawName.Trim() && x.Deleted == false))
                        {
                            response.SetFailed("此法律法规已存在");
                            return response;
                        }
                        var entryEntity = _dbContext.Law_Law.Attach(entity);
                        entryEntity.Property(p => p.ModifiedBy).IsModified = false;
                        entryEntity.Property(p => p.ModifiedOn).IsModified = false;
                        entity.Deleted = false;
                        entity.SubState = "未下发";
                        entity.State = "未审核";
                        entity.CompanyName = "中国煤科";
                        entity.CompanyNo = "001";
                        entity.CreatedBy = CurrentUser.UserInfo?.UserName;
                        entity.CreatedOn = System.DateTime.Now;
                        entity.LawNo = "LAW001_" + RandomHelper.GetRandomizer(8, true, false, false, true, true);
                        _dbContext.SaveChanges();
                    }

                    response.SetSuccess("操作成功");
                }

            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }

    }
}
